from rest_framework import viewsets
from rest_framework.decorators import api_view
from .models import record, order
from rest_framework.response import Response
from .serializers import recordSerializer, orderSerializer
# Create your views here.


class recordViewSet(viewsets.ModelViewSet):
    queryset = record.objects.all()
    serializer_class = recordSerializer


class orderViewSet(viewsets.ModelViewSet):
    queryset = order.objects.all()
    serializer_class = orderSerializer


@api_view(['POST'])
def check_user(request):
    """
    验证用户
    """
    if request.method == 'POST':
        data = request.data
        # 创建订单
        orderRecord = order.objects.create(price=0)
        # 订单详情
        for i in data:
            record.objects.create(order=orderRecord,)
            price = 1 + i.price
        # 更新价格
            orderRecord.objects.update(price=1)


@api_view(['POST'])
def SubmitOrder(request):
    """
    提交订单
    """
    if request.method == 'POST':
        data = request.data
        # 创建订单
        price = 0.0
        orderRecord = order.objects.create(price=0)
        # 订单详情
        for postRecord in data.get('recordList'):
            record.objects.create(order=postRecord, Goods=postRecord.get('Goods'), count=postRecord.get('count'), price=postRecord.get('price'))
            price += postRecord.get('price') * postRecord.get('count')
        # 更新价格
        orderRecord.objects.update(price=price)
    return Response({
        "status": True,
        "data": "提交成功"
        })


